//
//  Me2DayOAuthViewController.m
//  CairnStory
//  www.cairnstory.com
//
//  Created by saturna on 11. 3. 16..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

//#import <WebKit/Webkit.h>
#import "Me2DayOAuthViewController.h"
#import "Me2DayOAuthViewDelegate.h"
#import "Me2DayOAuthResult.h"
#import "Me2DayUtil.h"
#import "JSON.h"


#pragma mark -
#pragma mark Me2DayOAuthViewController (PrivateMethods)

@interface Me2DayOAuthViewController (PrivateMethods)

- (void)tapBackButtonItem:(id)sender;
- (void)dismissView;
- (void)startSignIn;
- (void)startProgressIndicator;
- (void)stopProgressIndicator;
- (BOOL)finalRequest:(NSURLRequest*)request;

@end


#pragma mark -
#pragma mark constants define

#define kDefaultNavigationTitle @"me2day"
#define kAuthRequestURLString @"http://me2day.net/api/get_auth_url.json"
#define kAuthURLKey @"url"


#pragma mark -
#pragma mark Me2DayOAuthViewController

@implementation Me2DayOAuthViewController

@synthesize initialHTMLString = m_initialHTMLString;



- (id)initWithAppKey:(NSString*)appKey
		 andDelegate:(id<Me2DayOAuthViewDelegate,NSObject>)delegate
{
	self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil];
	//if (DEBUG) Me2Log(@"====> initWithAppKey");
	if (self == nil)
	{
		return self;
	}

	m_isFinalRedirect = NO;
	m_appKey = [appKey retain];
	m_delegate = [delegate retain];
	return self;
}


#pragma mark -
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	//if (DEBUG) Me2Log(@"====> viewDidLoad");

	[m_webView setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin |
	 UIViewAutoresizingFlexibleWidth |
	 UIViewAutoresizingFlexibleRightMargin |
	 UIViewAutoresizingFlexibleTopMargin |
	 UIViewAutoresizingFlexibleHeight |
	 UIViewAutoresizingFlexibleBottomMargin];
	m_webView.backgroundColor = [UIColor clearColor];


	if (self.initialHTMLString == nil)
	{
		NSString* htmlFormat = @"<style>"
								"<!--"
								"BODY, TD, TH, A, PRE, P, B, SPAN, CODE {"
								"	color: #000000;"
								"	font-family: Arial,Helvetica,Tahoma,Verdana,sans-serif;"
								"	font-size: 12px;"
								"	text-decoration: none;"
								"}"
								"TD.td_text {"
								"	font-weight: normal;"
								"	background-color: #FFFFFF;"
								"	font-size: 15px;"
								"}"
								"-->"
								"</style>"
								"<table width=\"300\" height=\"300\""
								"align=\"center\" valign=\"middle\""
								"border=\"0\" cellpadding=\"3\" cellspacing=\"1\">"
								"<tr>"
								"<td align=\"center\" valign=\"middle\" class=\"td_text\">"
								"잠시만 기다려 주십시오.<br>"
								"me2day와 연결중입니다."
								"<br>"
								"<br>"
								"<img src=\"%@\" width=\"214\" height=\"45\" border=\"0\"/>"
								"</td>"
								"</tr>"
								"</table>";

		NSString* me2dayLogoPath = [[NSBundle mainBundle] pathForResource:@"logo_me2day.png" ofType:nil];
		me2dayLogoPath = [[NSURL fileURLWithPath:me2dayLogoPath] absoluteString];

		self.initialHTMLString = [NSString stringWithFormat:htmlFormat, me2dayLogoPath];
	}
	if (self.initialHTMLString != nil)
	{
		[m_webView loadHTMLString:self.initialHTMLString baseURL:nil];
	}

	if (self.navigationItem.title == nil)
	{
		self.navigationItem.title = kDefaultNavigationTitle;
	}

	UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back"
																	  style:UIBarButtonItemStylePlain
																	 target:self
																	 action:@selector(tapBackButtonItem:)];
	self.navigationItem.leftBarButtonItem = barButtonItem;
	[barButtonItem release];
}


- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self startProgressIndicator];
	[self performSelector:@selector(startSignIn) withObject:nil afterDelay:1.0];
	[super viewWillAppear:animated];

}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)dealloc
{
	m_webView.delegate = nil;
	[m_webView release];
	[m_progressIndicatorView release];

	[m_appKey release];
	[m_initialHTMLString release];
	[m_delegate release];

    [super dealloc];
}





#pragma mark -
#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request
 navigationType:(UIWebViewNavigationType)navigationType
{
	//if (DEBUG) Me2Log(@"===> [%@]", [request URL]);
	if (m_isFinalRedirect == NO)
	{
		m_isFinalRedirect = [self finalRequest:request];
	}
	if (m_isFinalRedirect)
	{
		[self dismissView];
		return NO;
	}

	return YES;
}

- (void)webViewDidStartLoad:(UIWebView*)webView
{
	//if (DEBUG) Me2Log(@"===> [%@]", [webView.request URL]);
	[self startProgressIndicator];
}

- (void)webViewDidFinishLoad:(UIWebView*)webView
{
	//if (DEBUG) Me2Log(@"===> [%@]", [webView.request URL]);
	[self stopProgressIndicator];
}

- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error
{
	if (error.code == NSURLErrorCancelled || (error.code == 102 && [error.domain isEqual:@"WebKitErrorDomain"]))
	{
		return;
	}

	//if (DEBUG) Me2Log(@"===> error : %@", error);
	if (m_delegate != nil &&
		[m_delegate respondsToSelector:@selector(me2dayOAuthViewController:didFailWithError:)])
	{
		[self stopProgressIndicator];
		[m_delegate me2dayOAuthViewController:self
							 didFailWithError:error];
	}
	[self dismissView];
}




#pragma mark -
#pragma mark Me2DayOAuthViewController (PrivateMethods)

- (void)tapBackButtonItem:(id)sender
{
	m_isFinalRedirect = YES;
	if (m_delegate != nil &&
		[m_delegate respondsToSelector:@selector(me2dayOAuthViewControllerDidCancel:)])
	{
		[self stopProgressIndicator];
		[m_delegate me2dayOAuthViewControllerDidCancel:self];
		//return;
	}

	[self dismissView];
}

- (void)dismissView
{
	//if (DEBUG) Me2Log(@"===> topViewController - before -- %d", [[self navigationController] topViewController] == self);
	[self stopProgressIndicator];
	if (self.modalInPopover)
	{
		[[self navigationController] dismissModalViewControllerAnimated:NO];
	}
	else
	{
		[[self navigationController] popViewControllerAnimated:NO];
		if ([[self navigationController] topViewController] == self)
		{
			[self dismissView];
		}
	}
	//if (DEBUG) Me2Log(@"===> topViewController - after -- %d", [[self navigationController] topViewController] == self);
}


- (void)startSignIn
{
	m_webView.delegate = self;

	// --------------------
	// 인증토큰 요청
	NSURL* aURL = [[NSURL alloc] initWithString:kAuthRequestURLString];
	NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:aURL];
	[aURL release];

	[urlRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData];
	[urlRequest setTimeoutInterval:kHTTPRequestTimeout];
	[urlRequest setHTTPMethod:@"POST"];

	NSString* queryString = [NSString stringWithFormat:@"akey=%@",m_appKey];
	[urlRequest setHTTPBody:[queryString dataUsingEncoding:NSUTF8StringEncoding]];

	NSError* error = nil;
	NSHTTPURLResponse* urlResponse = nil;
	NSData* responseData = [NSURLConnection sendSynchronousRequest:urlRequest
												 returningResponse:&urlResponse
															 error:&error];
	[urlRequest release];
	if (error != nil)
	{
		if (DEBUG) Me2Log(@"===> Error : %@", error);
		if (m_delegate != nil &&
			[m_delegate respondsToSelector:@selector(me2dayOAuthViewController:didFailWithError:)])
		{
			[self stopProgressIndicator];
			[m_delegate me2dayOAuthViewController:self
								 didFailWithError:error];
		}
		[self dismissView];
		return;
	}

	NSString* responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	if (DEBUG) Me2Log(@"=====> responseString : %@", responseString);

	if (urlResponse != nil && [urlResponse statusCode] != 200)
	{
		error = [[NSError alloc] initWithDomain:@"etcErrDomain"
										   code:[urlResponse statusCode]
									   userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
												 responseString, NSLocalizedDescriptionKey,
												 nil]];
		[responseString release];

		if (m_delegate != nil &&
			[m_delegate respondsToSelector:@selector(me2dayOAuthViewController:didFailWithError:)])
		{
			[self stopProgressIndicator];
			[m_delegate me2dayOAuthViewController:self
								 didFailWithError:error];
		}
		[self dismissView];
		return;
	}

	NSDictionary* responseDic = [responseString JSONValue];
	if (DEBUG) Me2Log(@"=====> responseDic : %@", responseDic);

	if (responseDic == nil)
	{
		error = [[NSError alloc] initWithDomain:@"etcErrDomain"
										   code:101
									   userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
												 responseString, NSLocalizedDescriptionKey,
												 nil]];
	}
	else
	{
		if ([responseDic objectForKey:kAuthURLKey] == nil)
		{
			if ([responseDic objectForKey:@"code"] != nil)
			{
				error = [[NSError alloc] initWithDomain:@"me2dayErrDomain"
												   code:[[responseDic objectForKey:@"code"] intValue]
											   userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
														 [NSString stringWithFormat:@"%@\n(%@)",
														  [responseDic objectForKey:@"description"],
														  [responseDic objectForKey:@"message"]], NSLocalizedDescriptionKey,
														 nil]];
			}
			else
			{
				error = [[NSError alloc] initWithDomain:@"etcErrDomain"
												   code:101
											   userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
														 responseString, NSLocalizedDescriptionKey,
														 nil]];
			}
		}
	}
	[responseString release];

	if (error != nil)
	{
		if (m_delegate != nil &&
			[m_delegate respondsToSelector:@selector(me2dayOAuthViewController:didFailWithError:)])
		{
			[self stopProgressIndicator];
			[m_delegate me2dayOAuthViewController:self
								 didFailWithError:error];
		}
		[self dismissView];
		return;
	}

	// --------------------
	// 인증화면 요청
	aURL = [[NSURL alloc] initWithString:[responseDic objectForKey:kAuthURLKey]];
	NSURLRequest* aRequest = [[NSURLRequest alloc] initWithURL:aURL];
	[aURL release];

	m_webView.scalesPageToFit = YES;
	[m_webView loadRequest:aRequest];
	[aRequest release];
}


- (void)startProgressIndicator
{
	if ([m_progressIndicatorView isAnimating])
	{
		return;
	}
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

	m_progressIndicatorView.hidden = NO;
	[m_progressIndicatorView startAnimating];

	self.view.userInteractionEnabled = NO;
	//self.navigationBarUserInteractionEnabled = NO;
}
- (void)stopProgressIndicator
{
	if ([m_progressIndicatorView isAnimating] == NO)
	{
		return;
	}
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

	m_progressIndicatorView.hidden = YES;
	[m_progressIndicatorView stopAnimating];

	self.view.userInteractionEnabled = YES;
	//self.navigationBarUserInteractionEnabled = YES;
}


- (BOOL)finalRequest:(NSURLRequest*)request
{
	if ([[[request URL] host] isEqualToString:kAuthCallbackHost] &&
		[[[request URL] path] isEqualToString:kAuthCallbackPath])
	{
		//BOOL delegateCalled = NO;
		NSMutableDictionary* params = [[Me2DayUtil parseQueryString:[[request URL] query]] retain];
		Me2DayOAuthResult* authResult = [[Me2DayOAuthResult alloc] initWithDictionary:params andAppKey:m_appKey];
		//if (DEBUG) Me2Log(@"===> params : %@", params);
		[params release];

		if (authResult.isAuthorized)
		{
			if (m_delegate != nil &&
				[m_delegate respondsToSelector:@selector(me2dayOAuthViewController:didLoginWithAuthResult:)])
			{
				[self stopProgressIndicator];
				[m_delegate me2dayOAuthViewController:self
							   didLoginWithAuthResult:[authResult autorelease]];
			}
		}
		else
		{
			if (m_delegate != nil &&
				[m_delegate respondsToSelector:@selector(me2dayOAuthViewController:didRejectWithAuthResult:)])
			{
				[self stopProgressIndicator];
				[m_delegate me2dayOAuthViewController:self
							  didRejectWithAuthResult:[authResult autorelease]];
			}
		}

		return YES;
	}

	return NO;
}

@end
